<template>
  <div class="consultation">
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="进行考试" name="first">
      <div class="flex-center">
        <el-input v-model="key1" size="mini" style="width: 120px;" placeholder="关键字/词查询"></el-input>
        <el-button class="ml0" size="mini" type="primary" @click="getPapers(true)"
          >查询</el-button
        >
      </div>
        <div class="consultation-block">
          <h3>考试列表</h3>
          <div class="table">
            <el-table size="mini" :data="tableDataPaper" style="width: 100%">
              <el-table-column label="序号" type="index"> </el-table-column>
              <el-table-column prop="name" label="试卷名称"> </el-table-column>
              <el-table-column label="操作" width="250">
                <template slot-scope="scope">
                  <el-button
                    type="success"
                    size="mini"
                    @click="start(scope.row)"
                    >开始考试</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </div>

          <div class="pagination">
            <el-pagination
              background
              layout="prev, pager, next"
              :current-page.sync="currentPage"
              @current-change="getPapers"
              :page-size="pageSize"
              :total="total"
            >
            </el-pagination>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="评分查看" name="second">
        <div class="consultation-block">
          <h3>我的考试记录</h3>
          <div class="table">
            <el-table size="mini" :data="tableDataExam" style="width: 100%">
              <el-table-column label="序号" type="index"> </el-table-column>
              <el-table-column prop="stuTime" label="考试时间"> </el-table-column>
              <el-table-column prop="score" label="分数"> </el-table-column>
              <el-table-column label="操作" width="250">
                <template slot-scope="scope">
                  <el-button
                    type="success"
                    size="mini"
                    @click="view(scope.row)"
                    >查看试卷</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </div>

          <div class="pagination">
            <el-pagination
              background
              layout="prev, pager, next"
              :current-page.sync="currentPage2"
              @current-change="getExams"
              :page-size="pageSize"
              :total="total2"
            >
            </el-pagination>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="错题查看" name="third">
        <div class="filter">
          <el-select clearable size="mini" v-model="filter.type" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item"
              :label="item"
              :value="item">
            </el-option>
          </el-select>
          <el-input v-model="key2" size="mini" style="width: 120px;" placeholder="关键字/词查询"></el-input>
          <el-button type="primary" size="mini" @click="currentPage3 = 1;getWrongs()">查询</el-button>
        </div>
        
        <div class="consultation-block">
          <div class="table">
            <el-table size="mini" :data="tableDataWrong" style="width: 100%">
              <el-table-column label="序号" type="index"> </el-table-column>
              <el-table-column prop="question.name" label="题目名称"> </el-table-column>
              <el-table-column prop="type" label="类型"> </el-table-column>
              <el-table-column prop="question.score" label="分数"> </el-table-column>
              <el-table-column label="操作" width="250">
                <template slot-scope="scope">
                  <el-button
                    type="success"
                    size="mini"
                    @click="viewWrong(scope.row)"
                    >查看错题</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </div>

          <div class="pagination">
            <el-pagination
              background
              layout="prev, pager, next"
              :current-page.sync="currentPage3"
              @current-change="getWrongs"
              :page-size="pageSize"
              :total="total3"
            >
            </el-pagination>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
    <el-dialog
      :title="title"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="dialogVisible"
      width="60%"
      :before-close="handleClose"
    >
      <div class="paper-content">
        <div v-if="questions['填空'] && questions['填空'].length">
          <h4>填空</h4>
          <div v-for="(test, i) in questions['填空']" :key="i">
            <div class="name">
              <div>{{ i + 1 }}.</div>
              <div style="width: 80%;" v-html="test.name"></div>
              <div class="score">分数：{{ test.score }}</div>
            </div>
              <el-input
                :disabled="title != '开始考试'"
                style="width: 100%;margin-top: 10px;"
                v-for="(s, index) in test.answer"
                :key="index"
                v-model="s.answer"
                >
                </el-input
              >
          </div>
        </div>
        <div v-if="questions['单选'] && questions['单选'].length">
          <h4>单选</h4>
          <div v-for="(test, i) in questions['单选']" :key="i">
            <div class="name">
              <div>{{ i + 1 }}.</div>
              <div v-html="test.name"></div>
              <div class="score">分数：{{ test.score }}</div>
            </div>
            <el-radio-group :disabled="title != '开始考试'" v-model="test.answer">
              <el-radio
                style="width: 100%;margin-top: 10px;"
                v-for="(s, index) in test.selections"
                :key="index"
                :label="index"
                >
                  <div>
                    <div v-html="s.text"></div>
                  </div>
                </el-radio
              >
            </el-radio-group>
          </div>
        </div>
        <div v-if="questions['多选'] && questions['多选'].length">
          <h4>多选</h4>
          <div v-for="(test, i) in questions['多选']" :key="i">
            <div class="name">
              <div>{{ i + 1 }}.</div>
              <div v-html="test.name"></div>
              <div class="score">分数：{{ test.score }}</div>
            </div>
            <el-checkbox-group :disabled="title != '开始考试'" v-model="test.answer">
              <el-checkbox
                style="width: 100%;margin-top: 10px;"
                v-for="(s, index) in test.selections"
                :key="index"
                :label="index"
                >
                  <div>
                    <div v-html="s.text"></div>
                  </div>
                </el-checkbox
              >
            </el-checkbox-group>
          </div>
        </div>
        <div v-if="questions['判断'] && questions['判断'].length">
          <h4>判断</h4>
          <div v-for="(test, i) in questions['判断']" :key="i">
            <div class="name">
              <div>{{ i + 1 }}.</div>
              <div v-html="test.name"></div>
              <div class="score">分数：{{ test.score }}</div>
            </div>
            <el-radio-group :disabled="title != '开始考试'" v-model="test.answer">
              <el-radio
                style="width: 100%;margin-top: 10px;"
                v-for="(s, index) in test.selections"
                :key="index"
                :label="index"
                >
                  <div>
                    <div v-html="s.text"></div>
                  </div>
                </el-radio
              >
            </el-radio-group>
          </div>
        </div>
        <div v-if="questions['主观题'] && questions['主观题'].length">
          <h4>主观题</h4>
          <div v-for="(test, i) in questions['主观题']" :key="i">
            <div class="name">
              <div>{{ i + 1 }}.</div>
              <div v-html="test.name"></div>
              <div class="score">分数：{{ test.score }}</div>
            </div>
            <vue-editor
              :editorOptions="editorOption"
              v-model="test.answer"
              useCustomImageHandler
              @image-added="handleImageAdded"
            />
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button v-if="activeName == 'first'" type="primary" @click="jiaojuan"
          >交 卷</el-button
        >
        <el-button v-if="activeName == 'second'" type="primary" @click="dialogVisible = false"
          >关 闭</el-button
        >
      </span>
    </el-dialog>
    
    <el-dialog
      title="查看错题"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="dialogVisibleWrong"
      width="60%"
      :before-close="handleClose2"
    >
      <div class="paper-content">
        <div v-if="wrongDetail.type == '单选'">
          <div>
            <div class="name">{{ wrongDetail.name }}
              <span class="score">分数：{{ wrongDetail.score }}</span></div>
              <el-radio-group v-model="wrongDetail.answer">
                <el-radio
                  style="width: 100%;margin-top: 10px;"
                  v-for="(s, index) in wrongDetail.selections"
                  :key="index"
                  :label="index"
                  >{{ s.text }}</el-radio
                >
              </el-radio-group>
              <div style="color: red;margin-top: 10px;">正确答案：{{wrongDetail.selections.find(v => v.checked).text}}</div>
          </div>
        </div>
        <div v-if="wrongDetail.type == '多选'">
          <div>
            <div class="name">{{ wrongDetail.name }}
              <span class="score">分数：{{ wrongDetail.score }}</span></div>
              <el-checkbox-group :disabled="title != '开始考试'" v-model="wrongDetail.answer">
                <el-checkbox
                  style="width: 100%;margin-top: 10px;"
                  v-for="(s, index) in wrongDetail.selections"
                  :key="index"
                  :label="index"
                  >{{ s.text }}</el-checkbox
                >
              </el-checkbox-group>
              <div style="color: red;margin-top: 10px;">正确答案：{{wrongDetail.duicuoTxet}}</div>
          </div>
        </div>
        <div v-if="wrongDetail.type == '判断'">
          <div>
            <div class="name">{{ wrongDetail.name }}
              <span class="score">分数：{{ wrongDetail.score }}</span></div>
              <el-radio-group :disabled="title != '开始考试'" v-model="wrongDetail.answer">
                <el-radio
                  style="width: 100%;margin-top: 10px;"
                  v-for="(s, index) in wrongDetail.selections"
                  :key="index"
                  :label="index"
                  >{{ s.text }}</el-radio
                >
              </el-radio-group>
              <div style="color: red;margin-top: 10px;">正确答案：{{wrongDetail.selections.find(v => v.checked).text}}</div>
          </div>
        </div>
        <div v-if="wrongDetail.type == '主观题'">
          <div>
            <div class="name mb10">{{ wrongDetail.name }}
              <span class="score">分数：{{ wrongDetail.score }}</span></div>
            <el-input
              type="textarea"
              :disabled="title != '开始考试'"
              :rows="4"
              placeholder="请输入答案"
              v-model="wrongDetail.answer">
            </el-input>
            <div style="color: red;margin-top: 10px;">得分:{{wrongDetail.scoreGet}}</div>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button v-if="activeName == 'first'" type="primary" @click="jiaojuan"
          >交 卷</el-button
        >
        <el-button v-if="activeName == 'second'" type="primary" @click="dialogVisible = false"
          >关 闭</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import moment from 'moment'
import { VueEditor } from "vue2-editor";
import { getPaper, queryQuestionsByIds, addExam, getExam, getWrong } from "../service.js";
export default {
  name: "home",
  components: { VueEditor },
  mounted() {
    this.getPapers();
  },
  data() {
    return {
      editorOption: {
        modules: {
          toolbar: [
            ["bold", "italic", "underline", "strike"], //加粗，斜体，下划线，删除线
            // ['blockquote', 'code-block'], //引用，代码块
            // [{'header': 1}, {'header': 2}], // 标题，键值对的形式；1、2表示字体大小
            // [{'list': 'ordered'}, {'list': 'bullet'}], //列表
            // [{'script': 'sub'}, {'script': 'super'}], // 上下标
            // [{'indent': '-1'}, {'indent': '+1'}], // 缩进
            // [{'direction': 'rtl'}], // 文本方向
            // [{ size: ["small", false, "large", "huge"] }], // 字体大小
            // [{'header': [1, 2, 3, 4, 5, 6, false]}], //几级标题
            [{ color: [] }, { background: [] }], // 字体颜色，字体背景颜色
            // [{'font': []}], //字体
            [{ align: [] }], //对齐方式
            ["clean"], //清除字体样式
            ['image'] //上传图片
          ],
        },
        placeholder: "输入内容...",
      },
      tableDataPaper: [],
      tableDataExam: [],
      tableDataWrong: [],
      currentPage: 1,
      currentPage2: 1,
      currentPage3: 1,
      pageSize: 10,
      total: 0,
      total2: 0,
      total3: 0,
      activeName: "first",
      questions: {},
      dialogVisible: false,
      title: '',
      currentRow: {},
      options: [
        '单选', '多选', '判断', '主观题'
      ],
      filter: {
        name: '',
        type: ''
      },
      dialogVisibleWrong: false,
      wrongDetail: {},
      key1: '',
      key2: '',
    };
  },
  methods: {
    getPapers(init = false) {
      if (init = true) {
        this.currentPage = 1;
      }
      let params = {
        pageSize: this.pageSize,
        page: this.currentPage,
      };
      if (this.key1) {
        params.key = this.key1
      }
      getPaper(params).then((res) => {
        this.tableDataPaper = res.code === 200 ? res.data.data : [];
        this.total = res.data.total;
      });
    },
    getExams() {
      let params = {
        pageSize: this.pageSize,
        page: this.currentPage2,
        stuId: JSON.parse(localStorage.getItem('userInfo')).id,
      };
      getExam(params).then((res) => {
        this.tableDataExam = res.code === 200 ? res.data.data : [];
        this.total2 = res.data.total;
      });
    },
    handleClose2() {
      this.dialogVisibleWrong = false;
    },
    getExams() {
      let params = {
        pageSize: this.pageSize,
        page: this.currentPage2,
        stuId: JSON.parse(localStorage.getItem('userInfo')).id,
      };
      getExam(params).then((res) => {
        this.tableDataExam = res.code === 200 ? res.data.data : [];
        this.total2 = res.data.total;
      });
    },
    getWrongs() {
      let params = {
        pageSize: this.pageSize,
        page: this.currentPage2,
        stuId: JSON.parse(localStorage.getItem('userInfo')).id,
      };
      if (this.key2) {
        params.key = this.key2
      }
      if (this.filter.type) {
        params.type = this.filter.type
      }
      getWrong(params).then((res) => {
        this.tableDataWrong = res.code === 200 ? res.data.data : [];
        this.total3 = res.data.total;
      });
    },
    handleClick() {
      if (this.activeName == "first") {
        this.currentPage = 1;
        this.getPapers();
      } else if (this.activeName == "second") {
        this.currentPage2 = 1;
        this.getExams();
      } else {
        this.currentPage3 = 1;
        this.getWrongs();
      }
    },
    handleClose() {
      this.dialogVisible = false;
    },
    start(row) {
      console.log(row)
      this.currentPaper = row;
      queryQuestionsByIds({
        questions: row.questions,
      }).then((res) => {
        let total = res.data.map((v) => {
          let selections = [];
          let answer = ''
          if (v[0].selections) {
            selections = JSON.parse(v[0].selections);
          }
          if (v[0].type == '多选') {
            answer = []
          }
          if (v[0].type == '填空') {
            answer = []
            for (let s of selections) {
              answer.push({
              answer: ''
            })
            }
          }
          return {
            ...v[0],
            selections,
            answer
          };
        });
        this.questions = this.filterByType(total);
        console.log(this.questions)
        // 试卷展示顺序按照 填空、单选、多选、判断、主观题
        this.title = '开始考试'
        this.dialogVisible = true;
      });
    },
    filterByType(objects) {
      const groupedByType = objects.reduce((grouped, obj) => {
        // 如果grouped中还没有这个type，则创建一个空数组
        if (!grouped[obj.type]) {
          grouped[obj.type] = [];
        }
        // 将当前对象添加到对应type的数组中
        grouped[obj.type].push(obj);
        // 返回更新后的grouped对象
        return grouped;
      }, {}); // 初始值为一个空对象.
      return groupedByType;
    },
    jiaojuan() {
      // 没做完
      let mzw = false;
      console.log(this.questions)
      for (let key in this.questions) {
        let qs = this.questions[key]
        if (key == '填空') {
          for (let q of qs) {
            for (let a of q.answer) {
              if (!a.answer) {
                mzw = true;
              }
            }
          }
        } else {
          if (qs.filter(v => v.answer.length == 0).length) {
            mzw = true;
            break
          }
        }
      }
      if (mzw) {
        this.$message.error('还有题目没做完')
        return
      }
      return
      addExam({
        stuId: JSON.parse(localStorage.getItem('userInfo')).id,
        stuTime: moment().format('YYYY-MM-DD HH:mm:ss'),
        paperId: this.currentPaper.id,
        paperInfo: JSON.stringify(this.questions)
      }).then(res => {
        if (res.code == 200) {
          this.$message.success('提成成功')
          this.dialogVisible = false;
        }
      })
    },
    view(row) {
      this.currentRow = row
      this.questions = JSON.parse(row.paperInfo)
      this.title = '浏览考试'
      this.dialogVisible = true;
    },
    viewWrong(row) {
      this.dialogVisibleWrong = true;
      this.wrongDetail = JSON.parse(row.detail);
    },

    // 处理富文本编辑框的图片
    async handleImageAdded(file, Editor, cursorLocation, resetUploader) {
      const formData = new FormData();
      formData.append("file", file);
      var xhr = new XMLHttpRequest();
      xhr.open("post", "http://localhost:3000/upload");
      xhr.send(formData);
      xhr.onload = function () {
        if (xhr.status == 200) {
          let res = JSON.parse(xhr.responseText);
          const url = "http://localhost:3000/" + res.url;
          Editor.insertEmbed(cursorLocation, "image", url);
          resetUploader();
        }
      };
    },
  },
};
</script>

<style lang="scss" scoped>
h2 {
  text-align: center;
  margin-top: 20px;
  margin-bottom: 20px;
}
h4 {
  margin-bottom: 20px;
  font-size: 20px;
  color: #333;
}

.paper-content {
  max-height: 60vh;
  overflow: hidden;
  overflow-y: scroll;
  & > div {
    margin-bottom: 20px;
  }
  & > div>div {
    margin-bottom: 10px;
  }
  .name {
    // font-weight: bold;
    display: flex;
    gap: 10px;
  }
}
.mb10 {
  margin-bottom: 10px;
}
.score {
  font-weight: bold;
  color: #666;
  margin-left: 20px;
}
.filter {
  display: flex;
  align-items: center;
  gap: 10px;
}
.el-radio {
  display: flex;
}
</style>
